package lesson

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/gtime"
	"server/api/admin/lesson"
	"server/internal/dao"
	"server/internal/model"
	"server/internal/model/do"
	"server/internal/service"
)

type sLessonArticle struct {
}

func init() {
	service.RegisterLessonArticle(&sLessonArticle{})
}

func (s *sLessonArticle) Create(ctx context.Context, in *lesson.ArticleCreateReq) (out *lesson.ArticleCreateRes, err error) {
	out = new(lesson.ArticleCreateRes)
	out.ID, err = dao.LessonArticle.Ctx(ctx).Data(do.LessonArticle{
		CategoryId: in.CategoryId,
		Title:      in.Title,
		Summary:    in.Summary,
		ZhContent:  in.ZhContent,
		EnContent:  in.EnContent,
		CreatedBy:  service.SystemLogin().GetAdminID(ctx),
	}).InsertAndGetId()
	return
}

func (s *sLessonArticle) Update(ctx context.Context, in *lesson.ArticleUpdateReq) (out *lesson.ArticleUpdateRes, err error) {
	out = new(lesson.ArticleUpdateRes)
	out.Result, err = dao.LessonArticle.Ctx(ctx).Data(do.LessonArticle{
		CategoryId: in.CategoryId,
		Title:      in.Title,
		Summary:    in.Summary,
		ZhContent:  in.ZhContent,
		EnContent:  in.EnContent,
		UpdatedBy:  service.SystemLogin().GetAdminID(ctx),
	}).Where(do.LessonArticle{Id: in.ID}).UpdateAndGetAffected()
	return
}

func (s *sLessonArticle) Delete(ctx context.Context, in *lesson.ArticleDeleteReq) (out *lesson.ArticleDeleteRes, err error) {
	out = new(lesson.ArticleDeleteRes)
	out.Result, err = dao.LessonArticle.Ctx(ctx).Data(do.LessonArticle{
		DeletedAt: gtime.Now(),
		DeletedBy: service.SystemLogin().GetAdminID(ctx),
	}).Where(do.LessonArticle{Id: in.ID}).UpdateAndGetAffected()
	return
}

func (s *sLessonArticle) ListForAdmin(ctx context.Context, in *lesson.ArticleListReq) (out *lesson.ArticleListRes, err error) {
	out = new(lesson.ArticleListRes)
	out.List = make([]model.LessonArticleListItem, 0)
	err = dao.LessonArticle.Ctx(ctx).Page(in.Page, in.PageSize).ScanAndCount(&out.List, &out.Total, true)

	// 分类信息
	_ = dao.LessonCategory.Ctx(ctx).As("cate").Fields("cate.*").
		WhereIn("cate.id", gdb.ListItemValuesUnique(out.List, "CategoryId")).
		ScanList(&out.List, "CategoryInfo", "id:CategoryId")

	// 创建人
	_ = dao.SystemUser.Ctx(ctx).As("u").Fields("u.*").
		WhereIn("u.id", gdb.ListItemValuesUnique(out.List, "CreatedBy")).
		ScanList(&out.List, "CreatedAdmin", "id:created_by")

	// 更新人
	_ = dao.SystemUser.Ctx(ctx).As("u").Fields("u.*").
		WhereIn("u.id", gdb.ListItemValuesUnique(out.List, "UpdatedBy")).
		ScanList(&out.List, "UpdatedAdmin", "id:updated_by")

	return
}
